// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/testing/connectors/fuzzer_connector.h>
#include <pollux/vector/vector_fuzzer.h>

namespace kumo::pollux::connector::fuzzer {

FuzzerDataSource::FuzzerDataSource(
    const std::shared_ptr<const RowType>& outputType,
    const std::shared_ptr<connector::ConnectorTableHandle>& tableHandle,
    pollux::memory::MemoryPool* pool)
    : outputType_(outputType), pool_(pool) {
  auto fuzzerTableHandle =
      std::dynamic_pointer_cast<FuzzerTableHandle>(tableHandle);
  POLLUX_CHECK_NOT_NULL(
      fuzzerTableHandle,
      "TableHandle must be an instance of FuzzerTableHandle");

  vectorFuzzer_ = std::make_unique<VectorFuzzer>(
      fuzzerTableHandle->fuzzerOptions, pool_, fuzzerTableHandle->fuzzerSeed);
}

void FuzzerDataSource::addSplit(std::shared_ptr<ConnectorSplit> split) {
  POLLUX_CHECK_EQ(
      currentSplit_,
      nullptr,
      "Previous split has not been processed yet. Call next() to process the split.");
  currentSplit_ = std::dynamic_pointer_cast<FuzzerConnectorSplit>(split);
  POLLUX_CHECK(currentSplit_, "Wrong type of split for FuzzerDataSource.");

  splitOffset_ = 0;
  splitEnd_ = currentSplit_->numRows;
}

std::optional<RowVectorPtr> FuzzerDataSource::next(
    uint64_t size,
    pollux::ContinueFuture& /*future*/) {
  POLLUX_CHECK_NOT_NULL(
      currentSplit_, "No split to process. Call addSplit() first.");

  // Split exhausted.
  if (splitOffset_ >= splitEnd_) {
    currentSplit_ = nullptr;
    splitOffset_ = 0;
    splitEnd_ = 0;
    return nullptr;
  }

  const size_t outputRows = std::min(size, (splitEnd_ - splitOffset_));
  splitOffset_ += outputRows;

  auto outputVector = vectorFuzzer_->fuzzRow(outputType_, outputRows);
  completedRows_ += outputVector->size();
  completedBytes_ += outputVector->retained_size();
  return outputVector;
}

} // namespace kumo::pollux::connector::fuzzer
